package distrcomp;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.rmi.RemoteException;


public class ServerTrackerImpl extends Thread {
	private ShippingTracker trackObj;
	private Shipment shipment;
	
	//Constructor
	public ServerTrackerImpl(ShippingTracker trackObj, ShippingTracker notifier, Shipment shipment) {
		this.trackObj = (notifier == null) ? trackObj : notifier;
		this.shipment = shipment;
	}
	
	private void backupTracker() {
		try {
			FileOutputStream fileStream = new FileOutputStream("tracker.dat");
			ObjectOutputStream objectStream = new ObjectOutputStream(fileStream);
			objectStream.writeObject(this.trackObj);
			objectStream.close();
			System.out.println("Succesfully backed up tracker.");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("Error backing up.");
		}
	}
	
	private void restoreTracker() {
		try {
			FileInputStream fileStream = new FileInputStream("tracker.dat");
		    ObjectInputStream objectStream = new ObjectInputStream(fileStream);
		    ShippingTracker tr = ((ShippingTracker) objectStream.readObject());
		    objectStream.close();
		    this.trackObj = tr;
		    System.out.println("Restored succesfully.");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("Error restoring.");
		}
	}
	
	//Run-method
	public void run() {
		this.backupTracker();
		//this.restoreTracker();
		while(this.shipment.getShippingState() != ShippingState.ARRIVED) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			try {
				this.trackObj.updateStatus(this.shipment.getShippingState());
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	}
}